<?php

/**
 * 
 * @author yuxun
 *
 */
class RoutineCrossServerService extends Service{

    public static function indexHeader(){
        $header = array(
                'id'            => array('text' => '序号', 'width' => '80px'),
        		'cross_server_name'       => array('text' => '跨服名称', 'width' => '150px'),
                'server_list'   => array('text' => '包含服务器', 'width' => '300px'),
        		'node_name'     => array('text' => '节点名称', 'width' => '100px'),
        		'develop_id'    => array('text' => '开发ID', 'width' => '100px'),
        		'version'       => array('text' => '版本', 'width' => '60px'),
        		'ip'            => array('text' => 'IP', 'width' => '100px'),
        		'port'          => array('text' => '端口', 'width' => '80px'),
        		'end_time'      => array('text' => '结束时间', 'width' => '150px'),
        		'status'        => array('text' => '状态', 'width' => '120px'),
        		'synchro_time'  => array('text' => '同步时间', 'width' => '150px'),
        		'create_time'   => array('text' => '创建时间', 'width' => '150px'),
                'action'        => array('text' => '操作', 'width' => '60px'),
        );

        return $header;
    }
    
    //添加的同步可以到列表同步，但编辑的同步则编辑的时候一起同步
    public static function indexData($params){   	
    	$modRoutineCrossCerver = new ModRoutineCrossCerver();
        $result = $modRoutineCrossCerver->page($params);
        
    	$length = count($result['data']);
    	$synList = self::synList();
    	foreach($result['data'] as $k=>&$v){
    		$type = 1;
    		if($k == 0 && $length == 1){  //当前页只剩下一条数据时，删除之后需显示上一页的数据
    			$type = 2;
    		}  
    		$server_list =  self::getServer($v['id']); 		
    		$v['server_list'] = $server_list == ''? '':$server_list;
    		$end_time = $v['end_time'];
    		$now_time = time();
    	    $v['end_time'] = date('Y-m-d H:i:s', $v['end_time']);
    		$v['create_time']     = date('Y-m-d H:i:s', $v['create_time']);
    		$v['synchro_time'] = $v['synchro_time'] == ''? '':date('Y-m-d H:i:s', $v['synchro_time']);
    		$v['action']        .= ' <a href="'.PubFunc::buildBackUrl('/oss/?r=routineCrossServer/edit').'&id='.$v['id'].'">编辑</a>';
    		$is_relieve = 1; //不可以解除
    		
    		if($v['status'] == 1 || $v['status'] == 4){ //添加后未同步，添加后同步失败
    			$v['action']        .= ' <a href="'.PubFunc::buildBackUrl('/oss/?r=routineCrossServer/delete',$type).'&id='.$v['id'].'" onclick="del()" confirm="是否要删除该条服信息?">删除</a>';
    		}

    		if($server_list != '' && $end_time < $now_time){
    			$v['action']        .= ' <a href="javascript:;" name="relieve_one" data-id="'.$v['id'].'">解除</a>';
    			$is_relieve = 2; //可以解除
    		} 

    		if($server_list != '' && $end_time > $now_time && $v['status'] == 2){  //同步的需强制解除，添加后未同步，添加后同步失败可以直接解除
    			//强制解除之后还需记录之前的关系
    			$v['action']        .= ' <a href="javascript:;" name="force_relieve_one" data-id="'.$v['id'].'">强制解除</a>';
    		}
    		if($server_list != '' && $end_time > $now_time && ($v['status'] == 1 || $v['status'] == 4)){
    			$v['action']        .= ' <a href="javascript:;" name="relieve_one" data-id="'.$v['id'].'">解除</a>';
    			$is_relieve = 2; //可以解除
    		}
    		
    		if($server_list != '' && $v['status'] != 2 && $v['status'] != 5){  //有服务器且未同步或者同步失败的可以进行同步操作
    			$v['action'] .= ' <a href="JavaScript:void(0);" name="rou_synchro_one" data-id="'.$v['id'].'" style="color:green;">同步</a>';
    		}
    		
    		$s_list = 1;
    		if($server_list == ''){
    			$s_list = 2;
    		}
    		
    		$id = $v['id'];
    		$checkbox = '<input value="'.$v['id'].'" data-status="'.$v['status'].'" data-list="'.$s_list.'" data-relieve="'.$is_relieve.'"  name="id" type="checkbox">&nbsp;&nbsp;';
    		$v['id'] = $checkbox.$v['id'];
    		
    		$v['status'] = $synList[$v['status']];
    	}
    	unset($v);
    
    	return $result;
    }
    
    public static function getServer($id){  	
    	$modRoutineCrossSer = new ModRoutineCrossSer();
    	$serverData = $modRoutineCrossSer->getServer($id);
    	$list = '';
    	foreach ($serverData as $key=>$val){
    		$list .= ','.$val['server_name'].'('.$val['server_num'].')';
    	}
    	$list = substr($list, 1);
    	return $list;
    }
    
   

    public static function doAdd($params){
        $user = AccAuth::me();
        
        if($params['end_time'] == ''){
        	//为空的时候，根据跨服周期来计算结束时间
        	$end_time = strtotime('+'.$params['cycle'].' day');
        }else{
        	$end_time = strtotime($params['end_time']);
        }
        $end_time = strtotime(date('Y-m-d H:i:00',$end_time));

        $modRoutineCrossCerver = new ModRoutineCrossCerver();
        $modRoutineCrossCerver->game          = $params['g'];
        $modRoutineCrossCerver->cross_server_name   = $params['cross_server_name'];
        $modRoutineCrossCerver->node_name       = $params['node_name'];
        $modRoutineCrossCerver->ip       = $params['ip'];
        $modRoutineCrossCerver->port       = $params['port'];
        $modRoutineCrossCerver->end_time       = $end_time;
        $modRoutineCrossCerver->create_user   = $user['UserID'];
        $modRoutineCrossCerver->create_time   = time();
        $modRoutineCrossCerver->update_user   = $user['UserID'];
        $modRoutineCrossCerver->update_time   = time();
        $modRoutineCrossCerver->version = $params['version'];
        $modRoutineCrossCerver->develop_id = $params['develop_id'];
        $result = $modRoutineCrossCerver->save();
        if($result !== false){
        	//记录常规跨服服务器与服务器的关系
        	$server_array = $params['server_id'];
        	$modRoutineCrossSer = new ModRoutineCrossSer();
        	$server = array();
        	foreach ($server_array as $key=>$val){
        		if($val == ''){
        			continue;
        		}
        		$data = array();
        		$data['server_id'] = $val;
        		$data['routine_id'] = $modRoutineCrossCerver->id;
        		array_push($server, $data);
        	}
        	$modRoutineCrossSer->addmuch($server);
        }
        return $result;
    }

    public static function doEdit($id, $params){
        if(empty($id)) return array('state'=>false,'msg'=>'非法参数');
        $user = AccAuth::me();
        
        if($params['end_time'] == ''){
        	//为空的时候，根据跨服周期来计算结束时间
        	$end_time = strtotime('+'.$params['cycle'].' day');
        }else{
        	$end_time = strtotime($params['end_time']);
        }
        $end_time = strtotime(date('Y-m-d H:i:00',$end_time));

        $modRoutineCrossCerver = new ModRoutineCrossCerver();
        $update = array();
        $update['game']         = $params['g'];
        $update['cross_server_name']  = $params['cross_server_name'];
        $update['node_name']       = $params['node_name'];
        $update['ip']       = $params['ip'];
        $update['port']       = $params['port'];
        $update['end_time']       = $end_time;
        $update['update_user']  = $user['UserID'];
        $update['update_time']  = time();
        $update['version'] = $params['version'];
        $update['develop_id'] = $params['develop_id'];
        $result = $modRoutineCrossCerver->updateByPk($id, $update);
        if($result !== false){
        	//先删除常规跨服服务器与服务器的关系
        	$modRoutineCrossSer = new ModRoutineCrossSer();
        	$modRoutineCrossSer->deleteAll('routine_id=:routine_id', array(':routine_id'=>$id));
        	
        	//记录常规跨服服务器与服务器的关系
        	$server_array = $params['server_id'];
        	$server = array();
        	foreach ($server_array as $key=>$val){
        		if($val == ''){
        			continue;
        		}
        		$data = array();
        		$data['server_id'] = $val;
        		$data['routine_id'] = $id;
        		array_push($server, $data);
        	}
        	$modRoutineCrossSer->addmuch($server);
        	
        	//同步start
        	$send_data = array();
        	$version = $params['version'];
        	$crossnode = $params['node_name'];
        	$gamenodes = self::getServerName($id);
        	
        	$d = array();
        	$d['version'] = $version;
        	$d['crossnode'] = $crossnode;
        	$d['gamenodes'] = $gamenodes;
        	
        	$extend_data = array();
        	$extend_data['ip'] = $params['ip'];
        	$extend_data['port'] = $params['port'];
        	$d['extend_data'] = $extend_data;
        	$send_data[$crossnode] = $d;
        	$out = self::send($send_data,1);
        	//记录同步情况
        	if($out['status'] == 1){  //成功
        		$status = 2;
        	}
        	if($out['status'] == 0){  //失败
        		$status = 5;
        	}
        	$modRoutineCrossCerver->updateRoutineForIds($status,time(),$id);
        	//同步end
        }
        return $result;
        
    }
    

    public static function get($id){
         $modRoutineCrossCerver = new ModRoutineCrossCerver();
         $obj = $modRoutineCrossCerver->findByPk($id);
        if($obj){
            $info = $obj->getAttributes();
            $info['end_time']  = empty($info['end_time']) ? '' : date('Y-m-d H:i:s', $info['end_time']);
            
            $modRoutineCrossSer = new ModRoutineCrossSer();
            $serverData = $modRoutineCrossSer->getServer($id);
            $item = array();
            foreach ($serverData as $key=>$val){
            	$item[$val['id']] = $val['server_name'].'('.$val['server_num'].')';
            }
            $info['item'] = $item;
            return $info;
        }else{
            return false;
        }
    }

    /*
     * 去重
     */
    public static function crepeat($id = 0, $field, $val,$g){
    	$modRoutineCrossCerver = new ModRoutineCrossCerver();
    	$conut = $modRoutineCrossCerver->crepeat($id, $field, $val,$g);
    	return $conut;
    }
    
    public static function delete($id){
    	if(empty($id)) return false;
    
    	$modRoutineCrossCerver = new ModRoutineCrossCerver();
    	$modRoutineCrossCerver->deleteByPk($id);
    	
    	//删除常规跨服服务器与服务器的关系
    	$modRoutineCrossSer = new ModRoutineCrossSer();
    	$modRoutineCrossSer->deleteAll('routine_id=:routine_id', array(':routine_id'=>$id));
    	
    	return true;
    }
    
    /**
     * 查询已经被使用的了服
     * @param unknown $routine_id
     * @return multitype:unknown
     */
    public static function useServer($routine_id){
    	$modRoutineCrossSer = new ModRoutineCrossSer();
    	$useList_obj = $modRoutineCrossSer->getUseServer($routine_id);
    	$useList = array();
    	foreach ($useList_obj as $key=>$val){
    		$useList[] = $val['server_id'];
    	}
//     	echo '<pre/>';
//     	var_dump($useList);exit;
    	return $useList;
    }
    
    /**
     * 获取剔除(剔除 测试服（测试服需要tab不为0的才可以）、审核服 )的服务器
     * @return multitype:string
     */
    public static function fitServer(){
    	//(剔除 测试服（测试服需要tab不为0的才可以）、审核服 )
    	$game = PubBase::getCurrentGame();

    	$where = array();
    	$where['g'] = $game;
    	$modServer = new ModServer();
    	$serverList = $modServer->select($where);
    	$nList = array();
    	$server_ids = '';
    	foreach ($serverList as $key=>$val){
    		if($val['check_flag'] != 3){ //剔除审核服
    			$server_ids .= $val['id'] . ', ';
    			$nList[$val['id']] = $val;
    		}
    	}
    	
    	$server_ids = substr($server_ids,0,strlen($server_ids)-2);

    	$modServerChannel = new ModServerChannel();
    	$serverChannelList = $modServerChannel->selectServerChannel($server_ids, $game);
    	foreach ($serverChannelList as $key=>$val){  //如果是备选服这unset(tab=0)
    		if($val['tab'] != 0 && $val['check_flag'] == 1){
    			unset($nList[$val['server_id']]);
    		}
    	}
    	
    	$list = array();
    	foreach ($nList as $key=>$val){
    		$list[$val['id']] = $val['server_name'].' ('.$val['server_num'].')';
    	}

    	return $list;
    }
    
    /**
     * 删除ids常规跨服与服务器的关系
     * @param unknown $ids
     */
    public static function relieve($ids){
    	$modRoutineCrossSer = new ModRoutineCrossSer();
    	$result = $modRoutineCrossSer->deleteForRoutineIds($ids);
    	if($result !== false){
    		$out = array('status'=>1,'msg'=>'操作成功','data'=>'');
    	}else{
    		$out = array('status'=>0,'msg'=>'操作失败','data'=>'');
    	}
    	
    	return $out;
    }
    
    /**
     * 强制性解除
     * @param unknown $ids
     */
    public static function forcerelieve($ids){
    	$user = AccAuth::me();
    	$modRoutineCrossSer = new ModRoutineCrossSer();
    	//先将要强制解除关系的跨服数据记录到 强制解除记录表
    	$modRoutineCrossCerver = new ModRoutineCrossCerver();
    	$list = $modRoutineCrossCerver->getRoutineForIds($ids);
    	foreach ($list as $key=>$val){
    		$modForceRoutineCrossCerver = new ModForceRoutineCrossCerver();
    		$modForceRoutineCrossCerver->game = $val['game'];
    		$modForceRoutineCrossCerver->cross_server_name = $val['cross_server_name'];
    		$modForceRoutineCrossCerver->node_name = $val['node_name'];
    		$modForceRoutineCrossCerver->ip = $val['ip'];
    		$modForceRoutineCrossCerver->port = $val['port'];
    		$modForceRoutineCrossCerver->end_time = $val['end_time'];
    		$modForceRoutineCrossCerver->create_user   = $user['UserID'];
    		$modForceRoutineCrossCerver->create_time   = time();
    		$modForceRoutineCrossCerver->update_user   = $user['UserID'];
    		$modForceRoutineCrossCerver->update_time   = time();
    		$mmresult = $modForceRoutineCrossCerver->save();
    		if($mmresult !== false){
    			$routine_server_obj = $modRoutineCrossSer->findAllByAttributes(array('routine_id'=>$val['id']));
    			$crossSerData = array();
    			foreach ($routine_server_obj as $k=>$v){
    				$d = array();
    				$d['routine_id'] = $modForceRoutineCrossCerver->id;
    				$d['server_id'] = $v['server_id'];
    				array_push($crossSerData, $d);
    			}
    			$modForceRoutineCrossSer = new ModForceRoutineCrossSer();
    			$modForceRoutineCrossSer->addmuch($crossSerData);
    		}
    	}
    	
    	//记录完成之后删除ids常规跨服与服务器的关系
    	$modRoutineCrossSer = new ModRoutineCrossSer();
    	$result = $modRoutineCrossSer->deleteForRoutineIds($ids);
    	if($result !== false){
    		$out = array('status'=>1,'msg'=>'操作成功','data'=>'');
    	}else{
    		$out = array('status'=>0,'msg'=>'操作失败','data'=>'');
    	}
    	 
    	return $out;
    }
    
    public static function forceViewHeader(){
    	$header = array(
    			'id'            => array('text' => '序号', 'width' => '80px'),
    			'cross_server_name'       => array('text' => '跨服名称', 'width' => '150px'),
    			'server_list'   => array('text' => '包含服务器', 'width' => '300px'),
    			'node_name'     => array('text' => '节点名称', 'width' => '100px'),
    			'develop_id'    => array('text' => '开发ID', 'width' => '100px'),
    			'version'       => array('text' => '版本', 'width' => '60px'),
    			'ip'            => array('text' => 'IP', 'width' => '100px'),
    			'port'          => array('text' => '端口', 'width' => '80px'),
    			'end_time'      => array('text' => '结束时间', 'width' => '150px'),
    			'create_time'   => array('text' => '解除时间', 'width' => '150px'),
    	);
    
    	return $header;
    }
    
    public static function forceView($params){
    	$modForceRoutineCrossCerver = new ModForceRoutineCrossCerver();
    	$data = $modForceRoutineCrossCerver->select($params);
    	
    	foreach($data as &$v){
    		 $v['end_time'] = date('Y-m-d H:i:s', $v['end_time']);
    		 $v['create_time'] = date('Y-m-d H:i:s', $v['create_time']);
    		 
    		 $server_list =  self::getForceServer($v['id']);
    		 $v['server_list'] = $server_list == ''? '':$server_list;
    	}
    	unset($v);
    	return $data;
    }
    
    public static function getForceServer($id){
    	$modForceRoutineCrossSer = new ModForceRoutineCrossSer();
    	$serverData = $modForceRoutineCrossSer->getServer($id);
    	$list = '';
    	foreach ($serverData as $key=>$val){
    		$list .= ','.$val['server_name'].'('.$val['server_num'].')';
    	}
    	$list = substr($list, 1);
    	return $list;
    }
    
    
    /**
     * 同步
     * @param unknown $ids
     */
    public static function rouSynchro($ids){   	
    	$modRoutineCrossCerver = new ModRoutineCrossCerver();
    	$list = $modRoutineCrossCerver->getRoutineForIds($ids);
    	$params = array();
    	foreach ($list as $key=>$val){
    		$version = $val['version'];
    		$crossnode = $val['node_name'];
    		$gamenodes = self::getServerName($val['id']);
    		
    		$d = array();
    		$d['version'] = $version;
    		$d['crossnode'] = $crossnode;
    		$d['gamenodes'] = $gamenodes;
    		
    		$extend_data = array();
    		$extend_data['ip'] = $val['ip'];
    		$extend_data['port'] = $val['port'];
    		$d['extend_data'] = $extend_data;
    		$params[$crossnode] = $d;
    	}
    	$out = self::send($params,1);
    	//记录同步情况
    	if($out['status'] == 1){  //成功
    		$status = 2;
    	}
    	if($out['status'] == 0){  //失败
    		$status = 4;
    	}
    	$modRoutineCrossCerver->updateRoutineForIds($status,time(),$ids);
    	return $out;
    }
    
    public static function send($params,$type=1){
    	if($type == 1){
    		$cmd_name = 'change_cross_net_data';
    	}
    	if($type == 2){
    		$cmd_name = 'refresh_cross_net_data';
    	}
    	if($type == 3){
    		$cmd_name = 'debug_show_info';
    	}
    	$data = array();
    	$data['node_name'] = 'global';
    	$data['service_name'] = '.scluster_noded';
    	$data['cmd_name'] = $cmd_name;
    	$data['params'] = $params;
    	$api = new ApiCrossSynchro();    	
    	$result = $api->call($data);
//     	echo '<pre/>';
//     	var_dump($result);exit;
     	//$result['state'] = true;
    	if($result['state']){ //同步成功
    		$out = array('status'=>1,'msg'=>'同步成功','data'=>$result['data']);
    	}else{//同步失败
    		$out = array('status'=>0,'msg'=>'同步失败,原因：'.$result['msg'],'data'=>'');
        }       
        return $out;
    }
    
    public static function getServerName($id){
    	$modRoutineCrossSer = new ModRoutineCrossSer();
    	$serverData = $modRoutineCrossSer->getServer($id);
    	$list = array();   	
    	foreach ($serverData as $key=>$val){
    		$list[] = $val['name'];
    	}
    	return $list;
    }
    
    public static function synList(){
    	return array(
    			'1' => '未同步(添加时)',
    			'2' => '已同步',
    			'3' => '未同步(编辑时)',
    			'4' => '同步失败(添加时)',
    			'5' => '同步失败(编辑时)',
    	);
    }
    
    public static function sHeader(){
    	$header = array(
    			'crossnode'   => array('text' => '节点名称', 'width' => '150px'),
    			'version'     => array('text' => '版本', 'width' => '150px'),
    			'gamenodes'   => array('text' => '包含服务器', 'width' => '150px'),
    			'ip'          => array('text' => 'IP', 'width' => '100px'),
    			'port'        => array('text' => '端口', 'width' => '160px'),	
    	);
    	return $header;
    }

}